package com.rural.bus;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.rural.bus.inteface.StartSelectAddress;
import com.rural.bus.model.MyPoiInfo;
import com.rural.bus.model.Railway;
import com.rural.bus.net.OnNetCallback;
import com.rural.bus.utils.DateUtil;
import com.rural.bus.utils.ProgressUtil;

/***
 * 马上用车，预约用车，日租的基类
 * @author majie
 *
 */
public abstract class CommonRailrayActivity extends BaseRailwayActivity implements StartSelectAddress{
	
	private TextView mTvDepart;
	private TextView mTvDest;
	
	private LinearLayout mLlDepart,mLlDest;
	
	/***
	 * 区分日租，半日租用
	 */
	protected int mergeId=1;
	
	@Override
	protected void initView() {
		super.initView();
		mTvDepart = (TextView) findViewById(R.id.tv_depart);
		mTvDest = (TextView) findViewById(R.id.tv_dest);
		
		mLlDepart=(LinearLayout) findViewById(R.id.ll_depart);
		mLlDest=(LinearLayout) findViewById(R.id.ll_dest);
		
		mLlDepart.setVisibility(View.VISIBLE);
		mLlDest.setVisibility(View.VISIBLE);

	}
	
	@Override
	protected void setListeners() {
		super.setListeners();
		
		mTvDest.addTextChangedListener(mWatcher);
		mTvDepart.addTextChangedListener(mWatcher);
        mTvTime.addTextChangedListener(mWatcher);
		mTvNumber.addTextChangedListener(mWatcher);
		mTvCarType.addTextChangedListener(mWatcher);
		
		mTvDepart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				startSelectAddress(REQUEST_MAP_START_ADDRESS);
			}
		});
		
		mTvDest.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				startSelectAddress(REQUEST_MAP_END_ADDRESS);
			}
		});
		
		mBtSubmit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if (taketime == 0) {
					toast("基本信息为空");
					return;
				}
				if (serviceTypeIndex != 2 && carTypeIndex == -1) {
					// 必须选择车型
					toast("基本信息为空");
					return;
				}
				if (isSelf) {
					passengerName = mCurrentUser.name;
					passengerPhone = mCurrentUser.phone;
				} else {
					passengerName = etPassengerName.getText().toString();
					passengerPhone = etPassengerPhone.getText().toString();
				}
				if (TextUtils.isEmpty(passengerName) || TextUtils.isEmpty(passengerName)) {
					toast("基本信息为空");
					return;
				}
				if (TextUtils.isEmpty(mTvDepart.getText()) || TextUtils.isEmpty(mTvDest.getText())) {
					toast("基本信息为空");
					return;
				}
				String remarks = mEtRemarks.getText().toString();
				ProgressUtil.showProgress(CommonRailrayActivity.this, "");
				mCurrentRailway = new Railway();
				mCurrentRailway.call(new Integer(mCurrentUser.userId), mCurrentUser.name, mStartAddress.name, mStartAddress.longitude, mStartAddress.latitude, mEndAddress.name, mEndAddress.latitude,
						mEndAddress.longitude, taketime, number, carTypeIndex, mOrderType, dis, mergeId, passengerPhone, remarks, new OnNetCallback() {

							@Override
							public void success(JSONObject object) {
								ProgressUtil.closeProgress();

								mCurrentUser.currentRailway = mCurrentRailway;
								// 叫车成功
								try {
									// 正常状态
									if (object.getInt("callStatus") == 0) {
										startActivity(WaitActivity.class);
									} else if (object.getInt("callStatus") == 2) {
										toast("附近没有司机");
									} else {
										toast("发生未知错误");
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}

							@Override
							public void fail(String error) {
								toast(error);
								ProgressUtil.closeProgress();

							}
						});
			}
		});
	}

	/***
	 * 选择地址
	 * @param v
	 * @param tag
	 */
	public void startSelectAddress(int requestCode) {
		Intent intent=new Intent(this, SearchAddressActivity.class);
		if(requestCode == REQUEST_MAP_END_ADDRESS){
			intent.putExtra("source", "end");
		}else{
			intent.putExtra("source", "start");
		}
		
		startActivityForResult(intent, requestCode);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == REQUEST_MAP_START_ADDRESS && resultCode == RESULT_MAP_START_ADDRESS){
			//处理上车地点
			mStartAddress = (MyPoiInfo)data.getSerializableExtra("address");
			mTvDepart.setText(mStartAddress.name);
		}
		
		if(requestCode == REQUEST_MAP_END_ADDRESS && resultCode == RESULT_MAP_END_ADDRESS){
			//处理选择的下车地点
			mEndAddress = (MyPoiInfo)data.getSerializableExtra("address");
			mTvDest.setText(mEndAddress.name);
		}
	}
	
	private void check() {
		if (TextUtils.isEmpty(mTvDepart.getText().toString())) {
			return;
		}
		if (TextUtils.isEmpty(mTvDest.getText().toString())) {
			return;
		}
		if (TextUtils.isEmpty(mTvTime.getText().toString())) {
			return;
		}
		if (TextUtils.isEmpty(mTvNumber.getText().toString())) {
			return;
		}
		if (TextUtils.isEmpty(mTvCarType.getText().toString())) {
			return;
		}
		ProgressUtil.showProgress(this, "");
		// 日租的时间格式和其他不一样
		if (serviceTypeIndex == 3) {
			taketime = DateUtil.getDate(mTvTime.getText().toString(), "yyyy年MM月dd日");
		} else {
			taketime = DateUtil.getDate(mTvTime.getText().toString(), "yyyy年MM月dd日 HH:mm");

		}
		// double distance =
		// DistanceUtil.GetShortDistance(mStartAddress.longitude,
		// mStartAddress.latitude, mEndAddress.longitude,
		// mEndAddress.latitude)/1000;
		// Log.d(TAG, "distance = "+distance);
		caculateNavigateDistance(mStartAddress.latitude, mStartAddress.longitude, mEndAddress.latitude, mEndAddress.longitude);
	}
	
	private void caculateNavigateDistance(double startLatitude, double startLongtitude, double endLatitude, double endLongtitude) {
		RoutePlanSearch routePlanSearch = null;
		routePlanSearch = RoutePlanSearch.newInstance();
		PlanNode startNode = PlanNode.withLocation(new LatLng(startLatitude, startLongtitude));
		PlanNode endNode = PlanNode.withLocation(new LatLng(endLatitude, endLongtitude));
		routePlanSearch.setOnGetRoutePlanResultListener(new GetRoutePlanResult());
		DrivingRoutePlanOption option = new DrivingRoutePlanOption().from(startNode).to(endNode).policy(DrivingRoutePlanOption.DrivingPolicy.ECAR_TIME_FIRST);
		routePlanSearch.drivingSearch(option);

	}
	
	protected TextWatcher mWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

		}

		@Override
		public void afterTextChanged(Editable arg0) {
			check();
		}
	};
	
	private class GetRoutePlanResult implements OnGetRoutePlanResultListener {
		private final String TAG = GetRoutePlanResult.class.getSimpleName();

		@Override
		public void onGetDrivingRouteResult(DrivingRouteResult result) {
			if (result != null && result.getRouteLines() != null && result.getRouteLines().size() > 0) {
				dis = Math.ceil(result.getRouteLines().get(0).getDistance() / 1000.f);// 导航距离;
				Log.d(TAG, "distance = " + dis);
				Railway.check(new Integer(mCurrentUser.userId), taketime, number, carTypeIndex, mOrderType, dis, mergeId, new OnNetCallback() {

					@Override
					public void success(JSONObject object) {
						ProgressUtil.closeProgress();
						Log.d(TAG, object.toString());
						try {
							String price = object.getString("result");
							mTvPrice.setText("约" + price + "元");
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void fail(String error) {
						ProgressUtil.closeProgress();
						Log.e(TAG, error);
//						toast(error);
						try {
							JSONObject object=new JSONObject(error);
							toast(object.getString("msg"));
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
			}
		}

		@Override
		public void onGetTransitRouteResult(TransitRouteResult arg0) {

		}

		@Override
		public void onGetWalkingRouteResult(WalkingRouteResult arg0) {

		}
	}


}
